package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.VO.AdUserVO;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserLoginService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;

@Service
public class AdUserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser>implements AdUserLoginService {
    @Override
    public ResponseResult userLogin(AdUserDto dto) {

        //校验参数
        if (dto == null || StringUtils.isNotBlank(dto.getName()) || StringUtils.isNotBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 根据用户名查询用户信息
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName())
                .eq(AdUser::getStatus, AdminConstants.AD_USER_ISSTATUS));
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名或密码错误");

        }
        //获取数据库密码、盐
        String password = adUser.getPassword();
        String salt = adUser.getSalt();
        //用户输入密码
        String newPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!password.equals(newPassword)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名或密码不正确");
        }
        adUser.setLoginTime(new Date());
        updateById(adUser);
        // 颁发token jwt 令牌
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        AdUserVO adUserVO = new AdUserVO();
        adUserVO.setId(adUser.getId());
        adUserVO.setEmail(adUser.getEmail());
        HashMap hashMap = new HashMap();
        hashMap.put("user", adUserVO);
        hashMap.put("token", token);
        return ResponseResult.okResult(hashMap);
    }
}
